#!/bin/bash
function errcho {
    echo "$@" 1>&2;
}

function pkgname {
    local pkg_entry=$(_pkgentry) || exit 1;
    local col=$(echo $pkg_entry | tr ':' ' ' | wc -w);
    if (( $col >= 3 )); then
		local n=$(echo $pkg_entry | cut -d: -f1);
		if [[ $n != "" ]]; then
			echo $n;
		else
			errcho "Can not get name info";
			exit 2;
		fi
	else
        errcho "Package header info too short ($pkg_entry)";
        exit 3;
    fi
}

function pkgversion {
    local pkg_entry=$(_pkgentry) || exit 1;
    local col=$(echo $pkg_entry | tr ':' ' ' | wc -w);
    if (( $col >= 3 )); then
		local v=$(echo $pkg_entry | cut -d: -f3);
		if [[ $v != "" ]]; then
			echo $v;
		else
			errcho "Can not get version info";
			exit 2;
		fi
	else
        errcho "Package header info too short ($pkg_entry)";
        exit 3;
    fi
}

function _pkgentry {
    if [ -r ./pkg.info ]; then
        echo `cat ./pkg.info | tr -s [:blank:] ':' | tr [:space:] '\n' | grep '^[^#]' | head -n1`;
    else
        errcho "Package info not found ($(pwd)/pkg.info)";
        exit 1;
    fi
}

function pkginstalled {
	if [ -z $1 ]; then
        errcho "pkginstalled: missing argument 1 (package name)";
        return 1;
    fi
	PKG_LIST="";
    PKG_VERSIONPATTERN=$(if [ -z $2 ]; then echo '*'; else echo "$2"; fi);
	for pkg in /usr/pkg/installed.db/${1}_${PKG_VERSIONPATTERN}_pkg.info; do
		if [ ! -r $pkg ]; then continue; fi
		PKG_INFO=$(echo $pkg | sed -e 's|/usr/pkg/installed.db/||') && \
		PKG_ENTRY=$(echo $PKG_INFO | grep -o -e '^.*_.*_pkg.info' | sed -e 's|_pkg.info||') && \
		PKG_NAME=$(echo $PKG_ENTRY | cut -d'_' -f1);
		if (($? != 0)); then
			errcho "pkginstalled: error while searching for installed packages $1";
			return 1;
		fi
		if [[ $(echo "$PKG_LIST" | grep "^${PKG_NAME}$") != "" ]]; then continue; fi
		PKG_LIST="$(echo "$PKG_LIST"; echo $PKG_NAME)";
	done
	echo "$PKG_LIST" | grep -v '^$';
}